from datetime import datetime, timedelta
from app.log_query import get_error_logs
from app.mailer import send_email
from app.utils import format_logs_to_html
from app.logger import get_logger

logger = get_logger('alert')

def check_and_alert(config, es_client):
    logger.info("开始执行每小时的错误日志检查...")
    es_conf = config.get_es_config()
    alert_conf = config.get_alerting_config()
    end_time = datetime.utcnow()
    start_time = end_time - timedelta(hours=1)
    error_logs = get_error_logs2(
        es_client=es_client.client,
        index_pattern=es_conf['index_pattern'],
        start_time=start_time,
        end_time=end_time
    )
    if not error_logs:
        logger.info("在过去一小时内没有发现错误日志。")
        return
    logger.info(f"发现了 {len(error_logs)} 条错误日志，准备发送邮件...")
    subject = f"{alert_conf['subject_prefix']} 发现 {len(error_logs)} 条新的错误日志 ({start_time.strftime('%Y-%m-%d %H:%M:%S')} - {end_time.strftime('%Y-%m-%d %H:%M:%S')})"
    body = format_logs_to_html(error_logs)
    send_email(
        smtp_config=config.get_smtp_config(),
        recipients=alert_conf['recipients'],
        subject=subject,
        body=body
    ) 